<?php

namespace App\Http\Controllers\Auth;

use App\Models\System\Admin;
use App\Models\User;
use App\Package\Message\Message;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\ResetPassword;
use Illuminate\Foundation\Auth\ResetsPasswords;

/**
 * 重置密码逻辑控制器
 *
 * Date: 07/05/2018
 * @author George
 * @package App\Http\Controllers\Auth
 */
class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

	/**
	 * 重置密码
	 *
	 * Date: 07/05/2018
	 * @author George
	 * @param ResetPassword $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
	public function password(ResetPassword $request)
	{
		$code = $request->get('code');
		$mobile = $request->get('mobile');
		$guard = $request->get('guard', 'user');

		// 判断用户类型
		if ($guard === 'user') {
			$user = User::query()->where('mobile', $mobile)->withTrashed()->first();
		} else {
			$user = Admin::query()->where('mobile', $mobile)->first();
		}

		if (!$user) {
			return failed('用户不存在', 404);
		}

		// 判断用户是否已禁用
		if ($user instanceof User && $user->trashed()) {
			return failed('该用户已被禁用', 404);
		}

		$password = $request->get('password');
		$message = new Message();
		$result = $message->verification($mobile, $code);

		if ($result) {
			$user->password = $password;
			$user->saveOrFail();
			return updated([]);
		} else {
			return failed('验证码不匹配，重置密码失败');
		}
	}
}
